package top.malaoshi.webmvc;


import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.malaoshi.sprout.utils.ResponseUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Thymeleaf 响应处理器
 * 当 启用 Thymeleaf 时，使用该类处理
 */
@Component
public class ThymeleafResponseHandler implements ResponseHandler{
    @Resource
    private TemplateEngine templateEngine;

    @Override
    public void handle(HttpServletResponse response, Object result) throws IOException {
        String template = null;

        Context context = new Context();

        if(result instanceof ModelAndView){
            ModelAndView mv = (ModelAndView)result;
            template = mv.getViewName();
            context.setVariables(mv.getModelMap());
        }
        // 渲染模板 (输出到变量（控制台）)
        String html = templateEngine.process(template, context);

        ResponseUtils.print(response,html);
    }
}
